
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import { getToken } from '@neu/biz-core/utils/auth'
import store from '@neu/biz-core/store'

class StompClient {
  constructor() {
    this.sock = null
    this.client = null
    this.connected = false
  }

  connect() {
    const that = this
    if (that.connected) return
    that.sock = new SockJS('/websocket?Authentication=' + getToken())
    that.client = Stomp.over(that.sock)
    that.client.heartbeat.outgoing = 10000
    that.client.heartbeat.incoming = 10000
    // that.client.debug = null
    that.client.connect({}, frame => {
      that.connected = true
      store.dispatch('app/setStompConnected', true)
      that.client.subscribe('/user/queue/notice', frame => {
        store.dispatch('notice/addNotification', JSON.parse(frame.body))
      })
    }, () => {
      that.connected = false
      that.reconnect()
    })
  }

  reconnect() {
    const that = this
    setTimeout(function() { that.connect.call(that) }, 10000)
  }

  disconnect() {
    const that = this
    if (that.client) {
      that.client.disconnect()
    }
    that.connected = false
  }

  subscribe(channel, callback) {
    const that = this
    if (store.getters.stompConnected) {
      return that.client.subscribe(channel, frame => {
        callback(frame.body)
      })
    }
  }
}

export default new StompClient()
